<?php

class pcontent{

	static $pDB;
	static $contentDir;
	/**
	 * Constructor for phylobyte Web Content class.
	 **/
	function __construct(){
		$this->pDB = $GLOBALS['PHYLOBYTEDB'];
		
		if(is_dir('../data')){
			$this->contentDir = '../data/';
		}else{
			$this->contentDir = 'data/';
		}

		if(!is_dir($this->contentDir.'images')){
			if(mkdir($this->contentDir.'images') && chmod($this->contentDir.'images',0777)){
				phylobyte::messageAddNotification('Successfully initialized image storage.');
			}else{
				phylobyte::messageAddError('Could not initialize image storage; you will not be able to upload any images.');
			}
		}
		if(!is_dir($this->contentDir.'files')){
			if(mkdir($this->contentDir.'files') && chmod($this->contentDir.'files',0777)){
				phylobyte::messageAddNotification('Successfully initialized file storage.');
			}else{
				phylobyte::messageAddError('Could not initialize file storage; you will not be able to upload any files.');
			}
		}

        /**
         * This is called at the beginning of each plugin that does
         * basic page management. It makes sure the database is set up.
         *
         * pc_items
         *  id
         *  type (page, section)
         *  name
         *  description
         *  date
         *  lastupdate
         *  weight
         *  content
         *  in_section
         *  in_navigation
		 *  i_is_visible
		 *  i_in_nav
         *
         */

        try{
            $this->pDB->exec("
                CREATE TABLE IF NOT EXISTS pc_items(
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                i_type TEXT,
                i_name TEXT,
                i_description TEXT,
                i_date TIMESTAMP DEFAULT 0,
                i_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                i_weight INTEGER,
                i_content TEXT,
                i_in_sec INTEGER,
                i_content_type TEXT,
                i_is_visible BOOLEAN,
                i_in_nav BOOLEAN,
                i_search_content TEXT,
                CONSTRAINT FOREIGN KEY (i_in_sec)
                  REFERENCES pc_items(id) ON DELETE CASCADE
			);");
        }catch(Exception $e){
            phylobyte::messageAddDebug($e);
        }

		/**
		 *  TABLE pc_tags
		 * 	id
		 * 	section
		 * 	tag
		 */

		try{
			$this->pDB->exec("
                CREATE TABLE IF NOT EXISTS pc_tags(
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                t_tag TEXT,
                t_section INTEGER,
                CONSTRAINT FOREIGN KEY (t_section)
                  REFERENCES pc_items(id)
			);");
		}catch(Exception $e){
			phylobyte::messageAddDebug($e);
		}

		/**
		 * TABLE pc_tagged
		 * 	id
		 * 	item
		 * 	tagid
		 */

		try{
			$this->pDB->exec("
                CREATE TABLE IF NOT EXISTS pc_tagged(
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                t_item INTEGER,
                t_tagid INTEGER,
                CONSTRAINT FOREIGN KEY (t_item)
                  REFERENCES pc_items(id),
                CONSTRAINT FOREIGN KEY (t_tagid)
                  REFERENCES pc_tags(id)
			);");
		}catch(Exception $e){
			phylobyte::messageAddDebug($e);
		}

	}

	function file_get_simple_type($ext){
		$type = null;
		switch($ext){
			case "doc":case "docx":case "dot":
			case "sxw":case "odt":case "ott":
			case "rtf":case "wps":case "wpf":
				$type = "wrd";
				break;
			case "xls":case "xlsx":case "sxc":case "ods":
			case "csv": case "mw": case "dia":
				$type = "srd";
				break;
			case "ppt": case "pptx":case "pdf": case "pub": case "pot":
			case "odp": case "otp": case "odg": case "otg": case "pps":
				$type = "ofs";
				break;
			case "txt": case "info": case "conf": case "config": case "cfg": case "nfo":
			case "f90": case "f95": case "java": case "cpp": case "c": case "asm": case "x86":
			case "cap": case "hex": case "dat": case "log":
				$type = "txt";
				break;
			case "html": case "shtml": case "xhtml": case "php": case "css": case "js":
			case "asp": case "aspx": case "xml":
				$type = "web";
				break;
			case "jpg": case "gif": case "jpeg": case "png": case "bmp": case "tif": case "tiff":
			case "xpm": case "svg": case "psd": case "ai": case "ps": case "eps": case "xcf": case "cell":
				$type = "img";
				break;
			case "wav": case "mp3": case "mp2": case "mp4": case "ogg": case "flac":
			case "wma": case "aac": case "aup": case "pcm": case "midi": case "mid":
			case "pls":
				$type = "snd";
				break;
			case "mov": case "avi": case "mpg": case "mpeg": case "wmv": case "ogm":
			case "swf": case "rm": case "nes":
				$type = "mov";
				break;
			case "zip": case "rar": case "gz": case "tar": case "7z": case "sitx": case "pk3":
			case "deb": case "rpm": case "run": case "iso": case "cue": case "cab":
			case "qvm": case "img": case "qcow": case "vdi": case "bak": case "pkg": case "img":
				$type = "cmx";
				break;
			case "exe": case "db": case "ini": case "lnk": case "reg": case "sys": case "bin": case "obj":
			case "dll": case "so": case "obj": case "bat": case "class":
				$type = "stp";
				break;
			default: $type = "---";
		}
		return $type;
	}
	
	function filesize_formatted($path){
		$size = filesize($path);
		$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
		$power = $size > 0 ? floor(log($size, 1024)) : 0;
		return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
	}
	
	/**
	 * Image management functions
	 **/

	private $colDir = '../data/images/';

	function images_collection_add($collectionName){
		if(@mkdir($this->colDir.$collectionName) && chmod($this->colDir.$collectionName, 0777) ){
			phylobyte::messageAddNotification('Successfully created new collection.');
			return true;
		}else{
			phylobyte::messageAddError('There was a problem creating the new collection.');
			return false;
		}
	}

	
	function delTree($dir) { 
		$files = array_diff(scandir($dir), array('.','..')); 
			foreach ($files as $file) { 
				(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
			} 
		return rmdir($dir);
	} 
	function images_collection_delete($collectionName, $empty = false){
		if($empty){
			if(@$this->delTree($this->colDir.$collectionName)){
				phylobyte::messageAddNotification('Successfully emptied and deleted collection.');
				return true;
			}else{
				phylobyte::messageAddError('There was a problem deleting the collection.');
				return false;
			}
		}
		if(@rmdir($this->colDir.$collectionName)){
			phylobyte::messageAddNotification('Successfully deleted collection.');
			return true;
		}else{
			phylobyte::messageAddError('There was a problem deleting the collection.');
			return false;
		}
	}

	function images_collection_list($template = null){

		$possibleCollections = scandir($this->colDir);
		$collections = null;

		//phylobyte::messageAddDebug(print_r($possibleCollections, true));

		if($template != null){
		
			//handle template
			$result = null;
			$i = 0;
			foreach($possibleCollections as $possibleCollection) {
				$i++;
				if(is_dir($this->colDir.$possibleCollection) && $possibleCollection != '.' && $possibleCollection != '..'){
					$collections[] = $possibleCollection;
					$needles = array(
						'**NUM',
						'**CollectionName',
						'**NumberOfImages',
						'**PRINTARRAY**',
						'**SixSmPreviews'
					);
					$replacements = array(
						$i,
						$possibleCollection,
						$this->images_collection_count($possibleCollection),
						print_r($collections, true),
						$this->images_collection_previews($possibleCollection, 6, 70, 'No Images to Preview <br/><br/>')
					);
					$result.=str_replace($needles, $replacements, $template);
				}
			}
			return $result;

		}else{
			return $collections;
		}
		
	}
	
	function siteURL(){
        $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $domainName = $_SERVER['HTTP_HOST'];
        return $protocol.$domainName.substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], "/admin/index.php"));
    }
	
	function images_collection_previews($collection, $numPreviews, $previewSize, $noPreviews = 'No Images to Preview'){
		$previewHTML = null;
		if(is_dir($this->colDir.'/'.$collection)){
			$possibleImages = scandir($this->colDir.$collection);
			$i = 0;
			$j = 0;
			while($i < $numPreviews && $j <= count($possibleImages) ){
				if(is_file($this->colDir.'/'.$collection.'/'.$possibleImages[$j])){
					$previewHTML.='
					<div class="collection-thumbnail-preview thumbnail-preview-'.($previewSize+8).'">
					<img src="'.$this->siteURL().'/plugins/image.php?source='.$this->siteURL().
					'/data/images/'.$collection.'/'.$possibleImages[$j].'&size='.$previewSize.'"
					style="margin: 4px;"/>
					</div>
					';
					$i++;
				}
				$j++;
			}
			if($i == 0){
				$previewHTML = $noPreviews;
			}
		}else{
			$previewHTML = 'Error generating previews.';
		}
		return $previewHTML;
	}
	
	function images_collection_count($collection){
		if(is_dir($this->colDir.'/'.$collection)){
			return count(scandir($this->colDir.'/'.$collection))-2;
		}else{
			return false;
		}
	}

    /**
     * Page Management Functions
     */

	function items_add($name, $type, $in_sec = null){

		$types = array(
			'item_page',
			'item_pages',
			'item_entries'
		);

		if(!in_array($type, $types)){
			phylobyte::messageAddError('Could not add new item; invalid type: '.$type);
			return false;
		}

		if(!$in_sec){
			$insert_name = $this->pDB->quote($name);
			$insert_type = $this->pDB->quote($type);
			$insert_timestamp = $this->pDB->quote(date('Y-m-d H:i:s',time()));

			try{
				$this->pDB->exec("
					INSERT INTO pc_items
					(i_name, i_type, i_date, i_content_type, i_weight)
					VALUES
					($insert_name, $insert_type, $insert_timestamp, 'wysiwyg', 0);
				");
				phylobyte::messageAddNotification('Successfully created new item.');
			}catch(Exception $e){
				phylobyte::messageAddDebug($e);
			}
		}else{
			$insert_name = $this->pDB->quote($name);
			$insert_type = $this->pDB->quote($type);
			$insert_timestamp = $this->pDB->quote(date('Y-m-d H:i:s',time()));
			$insert_in_sec = $this->pDB->quote($in_sec);

			try{
				$this->pDB->exec("
                    INSERT INTO pc_items
					(i_name, i_type, i_date, i_in_sec, i_is_visible, i_in_nav, i_content_type, i_weight)
					VALUES
					($insert_name, $insert_type, $insert_timestamp, $insert_in_sec, FALSE, FALSE, 'wysiwyg', 0);
				");
				phylobyte::messageAddNotification('Successfully created new item.');
			}catch(Exception $e){
				phylobyte::messageAddDebug($e);
			}
		}

	}

	function items_array($filter = null, $in = null){

		if(is_numeric($in)){
			$insecclause = "AND (items1.i_in_sec = ".$in." OR items1.id = ".$in.")";
		}elseif($in == 'top'){
			$insecclause = "AND items1.i_in_sec IS NULL";
		}else{
			$insecclause = '';
		}

		$items = $this->pDB->prepare("
			SELECT items1.*, items2.i_name AS i_parent_name,
				 IF(items1.i_in_sec IS NULL, IF(items1.i_type = 'item_entries' OR items1.i_type = 'item_pages', items1.id, -1), items1.i_in_sec) AS i_section
			FROM pc_items items1
			LEFT OUTER JOIN pc_items items2 ON items1.i_in_sec = items2.id
			WHERE items1.i_name LIKE '%$filter%' $insecclause
			ORDER BY i_section, i_in_sec, items1.i_weight ASC, items1.i_name;");
		$items->execute();
		$items = $items->fetchAll();

		return $items;
	}

	function item_delete($id){
		$clearInSec = $this->pDB->prepare("
			UPDATE pc_items SET i_in_sec = NULL WHERE i_in_sec = $id;
			");
		$clearInSec->execute();
		$delete = $this->pDB->prepare("
			DELETE FROM pc_items WHERE id = $id;
		");
		$delete->execute();
		phylobyte::messageAddNotification('Successfully deleted item.');
	}

	function item_get($id){
		$item = $this->pDB->prepare("
			SELECT * FROM pc_items WHERE id = $id;
		");
		$item->execute();
		$item = $item->fetchAll();
		return array_pop($item);
	}

	
}

include("../plugins/80 CMS Tools.p/CMS Tools.init");

$GLOBALS['PCON'] = new pcontent;

?>
